import 'package:df/page/web/language_locale.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/rendering.dart';
import 'package:df/page/login/login_page.dart';
import 'package:df/page/login/view_model/login_view_model.dart';
import 'package:df/page/privacy/privacy_page.dart';
import 'package:df/page/privacy/privacy_view.dart';
import 'package:df/page/sp_error_page.dart';
import 'package:df/page/sp_init_page.dart';
import 'package:df/page/router/router.dart';
import 'package:df/page/sms/sms_page.dart';
import 'package:df/page/web/web_page.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/utils/sp_key.dart';
import 'package:df/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:df/generated/l10n.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/foundation.dart';


bool isInit = false;
/// ok-Ft6Fan2WipBocq_NzlK2Yy790
void main() {
  // debugPaintSizeEnabled = kDebugMode;//TODO 调试边距
  Logger.level = Level.verbose;

  runApp(const MyApp());

  if (kDebugMode) {
    LogUtils.w("【调试】调试环境= ${kDebugMode}");
  } else {
    LogUtils.w("【调试】调试环境= ${kDebugMode}");
  }
}

/// 返回、首页、前进、用户
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    BuildContext appContext = context;
    LogUtils.d("【调试】测试日志功能= ${appContext}");

    // 竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    if(!isInit) {
      LogUtils.e('【是否两次】');
      isInit = true;
    } else {
      LogUtils.e('【是否两次】');
    }

    return makeFuture(context);
  }

  Widget makeFuture(BuildContext context) {
    LogUtils.i('【SP耗时初始化】1/4。。。');

    return FutureBuilder<SpUtils?>(// 1/4 耗时初始化
      //异步加载视图
      future: initSp(), //异步加载任务
      builder: (BuildContext context, AsyncSnapshot<SpUtils?> snapshot) {
        ConnectionState state = snapshot.connectionState;
        LogUtils.v('【SP】加载状态= ${state}');

        //none    无连接
        //waiting 等待中(未完成任何)
        //active  完成部分
        //done    完成
        if (state == ConnectionState.done) {
          LogUtils.e('【SP】加载完成');
          return makeProvider(context, true);
        } else {
          LogUtils.e('【SP】(未)加载完成');
          return makeProvider(context, false);
        }

      },
    );
  }

  Widget makeProvider(BuildContext context, bool isDone) {
    LogUtils.i('【动态语言】2/4。。。');

    if(isDone) {
      return MultiProvider(//TODO 2/4 动态语言
        providers: [
          ChangeNotifierProvider(create: (_) => LoginViewModel()),
          ChangeNotifierProvider(create: (_) => StringLocale()..init()),
        ],
        child: Builder(builder: (context) {
          return makeScreen(context, isDone);
        }),
      );
    } else {
      return makeScreen(context, isDone);
    }
  }

  Widget makeScreen(BuildContext context, bool isDone) {//TODO 3/4 屏幕适配
    LogUtils.i('【屏幕适配】3/4。。。');

    return ScreenUtilInit(//https://github.com/OpenFlutter/flutter_screenutil/blob/master/README_CN.md
      designSize: const Size(360, 690),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context ,child) {
        return makeMaterial(context, isDone);
      },);
  }

  Widget makeMaterial(BuildContext context, bool isDone) {
    LogUtils.i('【创建App】4/4。。。');

    Locale? spLocale;
    if(isDone) {
      // 这里的BuildContext可能无法找到StringLocale的Provider
      final spProvider = Provider.of<StringLocale>(context);
      spLocale = spProvider.locale;
      if (kDebugMode) {
        LogUtils.e('【语言】初始化Sp时语言= ${spLocale}');
        // ToastUtils.show('【语言】初始化Sp= \n ${spLocale?.languageCode}');
      }
    }

    ThemeData theme = ThemeData(
      colorScheme: ColorScheme.fromSeed(seedColor: Colors.cyan),
      //textTheme: const TextTheme(bodyMedium:TextStyle(fontSize: 30)),
      //fontFamily: 'PingFangFamily', // 替换为苹果字体
      useMaterial3: true,
    );

    // LogUtils.e('【语言】启动时系统语言= ${sysLocale}');
    return
      MaterialApp.router(
        debugShowCheckedModeBanner: false,//是否显示debug标签
        title: 'ODS',
        theme: theme,
        routerConfig: router,

        ///国际化【4/4】
        // 添加你的本地化代理
        localizationsDelegates: const [
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate
        ],
        // locale: locale ?? Localizations.localeOf(context),//TODO Sp??systemLocale
        locale: spLocale,
        supportedLocales: S.delegate.supportedLocales,//https://juejin.cn/post/7172442692972969992
        /// 监听系统语言切换
        localeListResolutionCallback: (locales, supportedLocales) {
          LogUtils.d('【调试】当前系统语言= $locales');
          if(locales != null && locales.isNotEmpty) {
            LogUtils.e('【调试】当前系统语言= ${locales.length}');
            LogUtils.e('【调试】当前系统语言= ${locales[0].languageCode}');
          }
          return;
        },
        ///国际化【4/4】

      );
  }


  /// 异步初始化SP。
  Future<SpUtils?> initSp() async {
    SpUtils? sp = await SpUtils.perInit();
    RouterId.wechatUnionId = SpUtils().get<String?>(SpKey.kSpWechatUnionId);
    RouterId.larkUnionId = SpUtils().get<String?>(SpKey.kSpLarkUnionId);
    RouterId.userId = SpUtils().get<String?>(SpKey.kSpUserId);
    LogUtils.v('【SP】初始化并取(微信)Id：${RouterId.wechatUnionId}');
    LogUtils.v('【SP】初始化并取(飞书)Id：${RouterId.larkUnionId}');
    LogUtils.v('【SP】初始化并取(用户)Id：${RouterId.userId}');
    return sp;
  }

}
